package com.googlecode.garbagecan.commons.clistudy.license;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang.math.NumberUtils;

public class CheckinCommandParser {
	private Options options;
	private Option optHelp;
	private Option optServer;
	private Option optFeature;
	private Option optVersion;
	private Option optNumber;
	
	public CheckinCommandParser() {
		optHelp = new Option("h", false, "print this help and exit");
		optServer = new Option("s", true, "feature server");
		optServer.setArgName("server");
		optFeature = new Option("f", true, "featuer name");
		optFeature.setArgName("feature");
		optVersion = new Option("v", true, "feature version");
		optVersion.setArgName("version");
		optNumber = new Option("n", true, "feature number");
		optNumber.setArgName("number");
		
		options = new Options();
		options.addOption(optHelp);
		options.addOption(optServer);
		options.addOption(optFeature);
		options.addOption(optVersion);
		options.addOption(optNumber);
	}

	public Command parse(String[] args) {
		CommandLineParser parser = new BasicParser();
		CommandLine cl = null;
		Command cmd;

		try {
			cl = parser.parse(options, args);
		} catch (ParseException ex) {
			ex.printStackTrace();
			return new CheckinHelpCommand();
		}
		
		Option[] opts = cl.getOptions();
		if (opts == null) {
			cmd = new CheckinHelpCommand();
		} else if (cl.hasOption(optHelp.getOpt())) {
			cmd = new CheckinHelpCommand();
		} else if (cl.hasOption(optServer.getOpt()) &&
				cl.hasOption(optFeature.getOpt()) &&
				cl.hasOption(optVersion.getOpt()) &&
				cl.hasOption(optNumber.getOpt())) {
			String server = cl.getOptionValue(optServer.getOpt());
			String feature = cl.getOptionValue(optFeature.getOpt());
			String version = cl.getOptionValue(optVersion.getOpt());
			if (!NumberUtils.isNumber(cl.getOptionValue(optNumber.getOpt()))) {
				System.out.println("The feature number must be a number.");
				System.exit(1);
			}
			int number = NumberUtils.toInt(cl.getOptionValue(optNumber.getOpt()));
			if (number <= 0) {
				System.out.println("The feature number must be a valid number.");
				System.exit(1);
			}
			cmd = new CheckinCommand(server, feature, version, number);
		} else {
			cmd = new CheckinHelpCommand();
		}
		return cmd;
	}
	
	public Options getOptions() {
		return this.options;
	}
}
